<?php

namespace App\Http\Controllers;

use App\CodeResponse;
class WxController extends Controller
{
       public function __construct()
       {
           header('Access-Control-Allow-Origin:*');
           header('Access-Control-Allow-Headers:Content-Type,Accept,Authorization');
           header('Access-Control-Allow-Methods:GET,POST,PUT,OPTIONS');
           if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
               return $this->fail(CodeResponse::DENY_LOGIN);
           }
       }

    //成功方法返回
    public function success($data = null, $info = '')
    {
        return $this->codeReturn(CodeResponse::SUCCESS, $data, $info);
    }
    //失败方法返回
    public function fail(array $codedResponse, $info = '', $data = null)
    {
        return $this->codeReturn($codedResponse, $data, $info);
    }

    private function codeReturn($codeResponse, $data = null, $info = '')
    {
        list($errno, $errmsg) = $codeResponse;
        $res = ['code' => $errno];
        if (is_array($data)) {
            $data        = array_filter($data, function ($item) {
                return $item !== null;
            });
            $res['data'] = $data;
        } elseif (!is_null($data)) {
            $res['data'] = $data;
        }
        $res['msg'] = $info ?: $errmsg;
        return response()->json($res);
    }
}
